package com.songcha.library_base.mvvm.base

import android.app.Application

abstract class BaseRefreshLoadMoreMultiViewModel<R:BaseRepository,RLST>(app: Application):BaseRefreshLoadMoreViewModel<R,RLST>(app) {

    protected open fun handleMultiDataListSuccess(newList:MutableList<RLST>,newRlmlst:MutableList<Any>){
        if(isRefreshing){
            if(newList.size == 0){
                onRefreshNoData()
            }else{
                rlst.value = newList
                rlmlst.value = newRlmlst
                onRefreshSuccess()
            }
        }else if(isLoadingMore){
            if(newList.size == 0){
                onLoadMoreNoData()
            }else{
                var start = 0
                var size = newList.size
                if(rlst.value == null || rlst.value!!.size == 0){
                    rlst.value = newList
                    rlmlst.value = newRlmlst
                }else{
                    //recyclerview must be shallow copy
                    val tmp = rlst.value!!
                    start = tmp!!.size
                    size = newList.size
                    tmp.addAll(newList)
                    rlst.value = tmp

                    rlmlst.value = newRlmlst

                }
                onLoadMoreSuccess(start,size)
            }

        }else{
            if(newList.size == 0){
                onLoadNoData()
            }else{
                rlst.value = newList
                rlmlst.value = newRlmlst
                onLoadSuccess()
            }
        }

    }

    protected open fun handleLoadMoreMultiDataListSuccess(newList:MutableList<Any>){
        if(!isLoadingMore) return

        if(newList.size == 0){
            onLoadMoreNoData()
        }else{
            if(rlst.value == null || rlst.value!!.size==0) return

            val notListCount = getNotListCount()

            var start = rlst.value!!.size - notListCount
            var size = newList.size

            val tmp = rlst.value!!
            tmp.addAll(getCastList(newList))
            rlst.value = tmp

            val tmp2 = rlmlst.value!!
            tmp2.addAll(newList)
            rlmlst.value = tmp2

            onLoadMoreSuccess(start,size)
        }

    }


    protected open fun getCastList(list:MutableList<Any>):MutableList<RLST>{
        val castList = mutableListOf<RLST>()
        for(item in list){
            castList.add(getCastItem(item))
        }
        return castList
    }

    abstract fun getNotListCount():Int

    abstract fun getCastItem(item:Any):RLST

}